package com.thiswhyme.easyexcel.service;

import com.thiswhyme.common.expection.BusinessException;
import com.thiswhyme.easyexcel.entity.InModel;
import com.thiswhyme.easyexcel.entity.OutModel;
import com.thiswhyme.easyexcel.utils.ExcelUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: thiswhyme
 * @date: 2021/9/15
 */
@Slf4j
@Service
public class ExcelService {

    /**
     * 导入导出demo
     * @param file
     * @param response
     */
    public void importAndExport(MultipartFile file, HttpServletResponse response) {
        List<InModel> ins;
        try (InputStream inputStream = file.getInputStream()) {
            ins = ExcelUtils.read(inputStream, InModel.class);
        } catch (IOException e) {
            log.error("导入失败", e);
            throw new BusinessException("导入失败");
        }

        if (!CollectionUtils.isEmpty(ins)) {
            List<OutModel> outs = new ArrayList<>();
            for (int i = 0; i < ins.size(); i++) {
                InModel in = ins.get(i);
                outs.add(new OutModel().setId(in.getId()).setName(in.getName()).setUrl("http://www.baidu.com" + i));
            }
            ExcelUtils.write(response, "【完成处理】" + file.getOriginalFilename(), OutModel.class, outs);
        }
    }
}
